<?php

class Application_Model_Order extends Application_Model_DomainObject implements Application_Model_PayInterface {

    /**
     * 待付款
     * @var unknown_type
     */
    const STATUS_PAYING = 0;

    /**
     * 已付款 
     */
    const STATUS_PAID = 1;

    /**
     * 已受理
     * @var unknown_type
     */
    const STATUS_CONFRIM = 2;

    /**
     * 已下单
     * @var unknown_type
     */
    const STATUS_UNSEND = 3;

    /**
     * 卖家已发货
     */
    const STATUS_SELLER_SENDED = 4;

    /**
     * 已入库 
     */
    const STATUS_INSTORE = 5;

    /**
     * 预订发货
     */
    const STATUS_SUBSCRIBE = 6;

    /**
     * 取消状态 
     */
    const STATUS_CANCEL = 10;

    /**
     * 超期发货
     */
    const STATUS_OUTTIME_UNSEND = 31;

    /**
     * 超期收货
     */
    const STATUS_OUTTIME_INSTORE = 41;

    /**
     * 超期财务风险
     */
    const STATUS_OUTTIME_FIN = 51;

    /**
     * 退货 
     */
    const STATUS_BANK = 11;

    /**
     *  部分退货
     */
    const STATUS_PartBank = 12;

    /**
     * 已完成
     * @var unknown_type
     */
    const STATUS_COMPLATED = 99;

    protected $_id;

    /**
     * 订单号
     */
    protected $_orderNo;
    //确认时间
    protected $_dateConfrim;
    //创建时间
    protected $_dateCreated;
    //入库时间
    protected $_dateInStore;
    //产品费用
    protected $_productTotal;
    //邮费
    protected $_shipFee;
    //状态
    protected $_status;
    //父订单
    protected $_parentId;
    //订单总额
    protected $_sum;

    /**
     * 优惠券
     */
    protected $_discount;
    //备注
    protected $_comment;
    //用户ID
    protected $_userId;
    //所有的商品
    private $_items;
    //店铺ID
    protected $_shopId;
    //采购单号,指在第三方网站上的订单号
    protected $_procureNo;
    //物流公司
    protected $_logistics;
    //物流单号
    protected $_logisticsNo;
    //采购日期
    protected $_dateProcure;
    protected $_problemContent; //问题原因
    protected $_ckPass;
    protected $_datePaid;
    protected $_operator;
    protected $_dateShip;
    protected $_problem; //问题代购 0正常 1问题 2问题解决
    protected $_isdelete; //0正常 1删除
    protected $_dateCancel;
    protected $_isAbnormal; //是否异常 0正常 1异常 2异常解决
    protected $_consignTime;
    protected $_scheme; // 异常处理方案
    protected $_rechangeStatus; //退换货状态

    /**
     * 正常
     */

    const Abnormal_Default = 0;

    /**
     * 少货
     */
    const Abnormal_Less = 1;

    /**
     * 发错货
     */
    const Abnormal_Error = 12;

    /**
     * 损坏
     */
    const Abnormal_Damage = 13;

    /**
     * 解决异常 
     */
    const Abnormal_Solve = 2;

    /**
     * 正常
     */
    const Problem_Default = 0;

    /**
     * 出现问题待用户回复
     */
    const Problem_Appear = 1;

    /**
     * 出现问题用户已回复
     */
    const Problem_User = 2;

    /**
     * 问题已解决
     */
    const Problem_Complete = 3;

    /**
     * 退货
     */
    const Scheme_Return = 1;

    /**
     * 换货
     */
    const Scheme_Change = 2;

    /**
     * 补发
     */
    const Scheme_Reissue = 3;

    /**
     * 退款
     */
    const Scheme_ReturnMoney = 4;

    /**
     * 恢复正常
     */
    const Scheme_Renormal = 5;

    /**
     * 重新操作
     */
    const Scheme_Reprocess = 11;

    /**
     * 成功
     */
    const Scheme_Succeed = 10;

    /**
     * 待退换货
     */
    const ReChange_Dispose = 1;

    /**
     * 待悠奇发包
     */
    const ReChange_Emit = 2;

    /**
     * 待卖家发包
     */
    const ReChange_Seller = 3;

    /**
     * 待完成
     */
    const ReChange_Reissue = 4;

    /**
     * 退换货完成
     */
    const ReChange_Complete = 10;

    private $_logisticsBy;

    public function getLogisticsBy() {
        if ($this->_logisticsBy == null) {
            $this->_logisticsBy = Application_Model_shipType::load($this->_logistics);
            if ($this->_logisticsBy == NULL)
                $this->_logisticsBy = new Application_Model_shipType();
        }
        return $this->_logisticsBy;
    }

    private $_emmis;

    public function getEmmis() {
        if ($this->_emmis == null) {
            $shipItem = Application_Model_shipType::load($this->_logistics);
            if ($shipItem && $shipItem->EmId != "") {
                $this->_emmis = Application_Model_Emmis::load($shipItem->EmId);
            }
            if ($this->_emmis == NULL)
                $this->_emmis = new Application_Model_Emmis();
        }
        return $this->_emmis;
    }

    /**
     * 返回订单中的商品
     * @return array
     */
    public function getItems() {
        if (NULL != $this->_items){ 
            return $this->_items;
        }
           
        if (isset($this->_id)){
            $this->_items = Application_Model_OrderItem::getByOrderId($this->_id);
        }else{
            $this->_items = array();
        }
        return $this->_items;
    }

    /**
     * 添加一个产品到订单中
     * @param Application_Model_OrderItem $orderItem
     */
    public function addItem(Application_Model_OrderItem $orderItem) {
        $this->getItems();

        array_push($this->_items, $orderItem);
    }

    private $_user;

    public function getUser() {
        if ($this->_user == NULL)
            $this->_user = Application_Model_User::load($this->_userId);
        return $this->_user;
    }

    /**
     * 从购物车生成一个订单
     * @param Application_Model_Cart $cart 购物车
     * @return Application_Model_Order
     */
    public static function fromCart(Application_Model_Cart $cart) {
        $order = new Application_Model_Order();
        $order->DateCreated = date('Y-m-d H:i:s');
        $order->Status = Application_Model_Order::STATUS_PAYING;
        $order->UserId = Application_Model_User::current()->Id;
        $productTotal = $cart->ProductTotal;
        $shipFee = $cart->ShipFeeTotal;
        $order->Scheme = 0;
        foreach ($cart->getItems() as $item) {
            $orderItem = new Application_Model_OrderItem();
            $orderItem->ProductId = $item->ProductId;
            $orderItem->Price = $item->Price;
            $orderItem->Quantity = $item->Quantity;
            $orderItem->ProductName = $item->ProductName;
            $orderItem->Comment = $item->Comment;
            $order->addItem($orderItem);
            //$productTotal += $item->Price;
            //$shipFee += $item->ShipFee;
        }
        $order->Sum = $productTotal + $shipFee;
        return $order;
    }

    public static function getStatusAll() {
        return array(
            Application_Model_Order::STATUS_PAID => "已付款"
            , Application_Model_Order::STATUS_CONFRIM => "已受理"
            , Application_Model_Order::STATUS_UNSEND => "已下单"
            , Application_Model_Order::STATUS_SELLER_SENDED => "卖家已发货"
            , Application_Model_Order::STATUS_INSTORE => "已入库"
            , Application_Model_Order::STATUS_OUTTIME_UNSEND => "超期未发货"
            , Application_Model_Order::STATUS_OUTTIME_INSTORE => "超期未收货"
            , Application_Model_Order::STATUS_OUTTIME_FIN => "超期财务风险"
        );
    }

    public function getStatusCorrect() {
        return array(
            Application_Model_Order::STATUS_CONFRIM => array("待受理", "已受理")
            , Application_Model_Order::STATUS_UNSEND => array("待下单", "已下单")
            , Application_Model_Order::STATUS_SELLER_SENDED => array("待卖家发货", "卖家已发货")
            , Application_Model_Order::STATUS_INSTORE => array("待入库", "已入库")
        );
    }

    public function getStatusNames() {
        $statusText = array(
            Application_Model_Order::STATUS_PAYING => "待付款"
            , Application_Model_Order::STATUS_PAID => "已付款"
            , Application_Model_Order::STATUS_CONFRIM => "已受理"
            , Application_Model_Order::STATUS_UNSEND => "已下单"
            , Application_Model_Order::STATUS_SELLER_SENDED => "卖家已发货"
            , Application_Model_Order::STATUS_INSTORE => "已入库"
            , Application_Model_Order::STATUS_SUBSCRIBE => "订单预订"
            , Application_Model_Order::STATUS_CANCEL => "取消"
            , Application_Model_Order::STATUS_BANK => "退货"
            , Application_Model_Order::STATUS_PartBank => "部分退货"
            , Application_Model_Order::STATUS_OUTTIME_UNSEND => "超期未发货"
            , Application_Model_Order::STATUS_OUTTIME_INSTORE => "超期未收货"
            , Application_Model_Order::STATUS_OUTTIME_FIN => "超期财务风险"
            , Application_Model_Order::STATUS_COMPLATED => "完成"
        );
        return $statusText[$this->_status];
    }

    public function getStatusText() {
        if ($this->_isAbnormal > 0 && ($this->_rechangeStatus)) {
            if ($this->_scheme == Application_Model_Order::Scheme_Return) {
                return $this->_rechangeStatus == Application_Model_Order::ReChange_Complete ? "退货完成" : "退货中";
            } else if ($this->_scheme == Application_Model_Order::Scheme_Change) {
                return $this->_rechangeStatus == Application_Model_Order::ReChange_Complete ? "换货完成" : "换货中";
            } else if ($this->_scheme == Application_Model_Order::Scheme_Reissue) {
                return $this->_rechangeStatus == Application_Model_Order::ReChange_Complete ? "补发完成" : "补发中";
            } else if ($this->_scheme == Application_Model_Order::Scheme_ReturnMoney) {
                return $this->_rechangeStatus == Application_Model_Order::ReChange_Complete ? "退款完成" : "退款中";
            } else {
                return $this->_isAbnormal == Application_Model_Order::Abnormal_Less ? "部分入库" : "错误包裹";
            }
        } else {
            $statusText = array(
                Application_Model_Order::STATUS_PAYING => "待付款"
                , Application_Model_Order::STATUS_PAID => "已付款"
                , Application_Model_Order::STATUS_CONFRIM => "已受理"
                , Application_Model_Order::STATUS_UNSEND => "已下单"
                , Application_Model_Order::STATUS_SELLER_SENDED => "卖家已发货"
                , Application_Model_Order::STATUS_INSTORE => "已入库"
                , Application_Model_Order::STATUS_SUBSCRIBE => "订单预订"
                , Application_Model_Order::STATUS_CANCEL => "取消"
                , Application_Model_Order::STATUS_BANK => "退货"
                , Application_Model_Order::STATUS_PartBank => "部分退货"
                , Application_Model_Order::STATUS_OUTTIME_UNSEND => "已下单"
                , Application_Model_Order::STATUS_OUTTIME_INSTORE => "卖家已发货"
                , Application_Model_Order::STATUS_OUTTIME_FIN => "卖家已发货"
                , Application_Model_Order::STATUS_COMPLATED => "完成"
            );
            return $statusText[$this->_status];
        }
    }

    public function saveSelf() {
        parent::save();
    }

    /**
     * 保存订单，并关联的把订单项也保存起来
     * 
     */
    public function save() {
        parent::save();
        foreach ($this->getItems() as $item) {
            $item->OrderId = $this->Id;
            $item->save();
        }
    }

    protected static function getDb() {
        return new Application_Model_DbTable_Order();
    }

    /**
     * 返回用户的订单列表
     * @param 用户ID $userId
     * @param 开始时间 $startTime
     * @param 结束时间 $endTime
     * @param 开始序号 $start
     * @param int $pageSize 一次返回数量
     * @return type 
     */
    public static function getByUser($userId, $startTime, $endTime, $start, $pageSize) {
        return Application_Model_Order::getDb()->getByUser($userId, $startTime, $endTime, $start, $pageSize);
    }

    /**
     * 根据指定的条件返回订单
     * @param int $orderId
     * @param int $memberId
     * @param date $startTime 开始时间
     * @param date $endTime 结束时间
     * @param int $status 订单状态
     * @param int $count
     * @param int $offset
     * @return 返回格式为 array('size'=>?,'list'=>?,'pages'=>?,'index'=>?) 
     * size为查询记录的总条数，list为返回的array型数据，pages是指有多少页，index为当前是哪一页 
     */
    public static function getByFilter($orderId, $memberId, $startTime, $endTime, $status, $keyword, $count, $offset) {
        $where = array();
        $and = '';
        if ($orderId != NULL) {
            $where['Id = '] = $orderId;
            $and = ' and ';
        }

        if ($memberId != NULL) {
            $where[$and . ' userId = '] = $memberId;
            $and = ' and ';
        }

        if ($startTime != NULL) {
            $where[$and . ' dateCreated >= '] = $startTime;
            $and = ' and ';
        }

        if ($endTime != NULL) {
            $where[$and . ' dateCreated <= '] = $endTime;
            $and = ' and ';
        }

        if ($status != NULL && $status != '') {
            $where[$and . ' status = '] = $status;
            $and = ' and ';
        }

        if ($keyword != NULL) {
            
        }

        return Application_Model_Order::getDb()->queryPage($where, 'dateCreated desc', $count, $offset);
    }

    public static function getUncomplate($userId) {
//    	return Application_Model_Order::getDb()->getUncomplate($userId);
        $where[" status !="] = Application_Model_Order::STATUS_CANCEL;
        $where[" and status != "] = Application_Model_Order::STATUS_INSTORE;
        $where[" and userId = "] = $userId;
        $where[" and isdelete != "] = 1;
        $where[" and (rechangeStatus is null or rechangeStatus != 10 ) and "] = 1;
        return self::getDao()->count($where);
    }

    public static function getCountByUserId($userId) {
        return self::getDao()->count(array("userId = " => $userId));
    }

    public static function getCountByStatus($userId, $status) {
        return Application_Model_Order::getDb()->count(array('userId' => $userId, 'status' => $status));
    }

    public static function getByNo($orderNo) {
        return Application_Model_Order::getDb()->queryOne(array('orderNo' => $orderNo));
    }

    public function getMoney() {
        return ($this->Sum - $this->Discount);
    }

    public function getPayName() {
        return '悠奇-代购';
    }

    public function getPayCommen() {
        return "代购流水号：U" . substr($this->_dateCreated, 0, 4) . $this->Id . substr($this->_dateCreated, 17, 1);
        ;
    }

    public function isRepeatPay() {
        if ($this->_status == self::STATUS_PAYING) {
            return true;
        }
        return false;
    }

    private $_shop;

    public function getShop() {
        if ($this->_shop == NULL)
            $this->_shop = new Application_Model_Shop($this->_shopId);
        return $this->_shop;
    }

    public function setPaid() {
        $this->Status = Application_Model_Order::STATUS_PAID;
        $this->datePaid = date("Y-m-d H:i:s");
    }

    public function getBillNo() {
        return $this->getOrderNum();
    }

    /**
     * 返回订单号
     * @return type 
     */
    public function getOrderNum() {
        return 'U' . substr($this->DateCreated, 0, 4) . $this->Id . substr($this->DateCreated, 17, 1);
    }

    /**
     * 代购唯一标识
     */
    public function getSoleNo() {
        return "D" . $this->_id;
    }

    public function getPayDescription() {
        return '代购订单';
    }

    public function canPay($userId) {
        if ($this->_status != Application_Model_Order::STATUS_PAYING)
            return FALSE;
        if ($this->_userId != $userId)
            return FALSE;
        return TRUE;
    }

    /**
     * 根据几个ID，创建一个空订单，供支付使用
     */
    public static function createByOrderIds($ids) {
        return Application_Model_OrderParent::createByOrderIds($ids);
    }

    /**
     * 获取该状态下的订单的数量
     * @param type $date 时间
     * @param type $status 状态
     */
    public static function countorder($orderSearch) {
        return Application_Model_Order::getDao()->count($orderSearch->getSearchFileds());
    }

    public static function getOrdercount($dateinbegin, $dateinend) {
        $where = "";
        $and = "";
        if ($dateinbegin != "" && $dateinend == "") {
            $where[" status != "] = Application_Model_Order::STATUS_PAYING;
            $and = " and ";
            $where[$and . " (status != "] = Application_Model_Order::STATUS_CANCEL;
            $where[")" . $and . " status != "] = Application_Model_Order::STATUS_BANK;
            $where[$and . " dateCreated > "] = $dateinbegin . " 00:00:00";
            $and = " and ";
            $where[$and . " dateCreated < "] = $dateinbegin . " 23:59:59";
            $result = Application_Model_Order::getDb()->queryAll($where);
            $i = strtotime($dateinbegin);
            $arrre[$i]["num"] = count($result);
            $arrre[$i]["ysje"] = 0;
            $arrre[$i]["zyf"] = 0;
            $arrre[$i]["bfyk"] = 0;
            if ($result) {
                foreach ($result as $value) {
                    $arrre[$i]["ysje"] = $arrre[$i]["ysje"] + $value->sum;
                    $arrre[$i]["zyf"] = $arrre[$i]["zyf"] + $value->shipFee;
                    if ($value->status == Application_Model_Order::STATUS_PartBank) {
                        $bftkItem = Application_Model_OrderItem::getByOrderId($value->id);
                        if ($bftkItem) {
                            foreach ($bftkItem as $key => $itemvalue) {
                                if ($itemvalue->status == 1) {
                                    $arrre[$i]["bfyk"] = $arrre[$i]["bfyk"] + ($itemvalue->quantity * $itemvalue->price);
                                }
                            }
                        }
                    }
                }
            }
        }
        if ($dateinend != "" && $dateinbegin == "") {
            $where[" status != "] = Application_Model_Order::STATUS_PAYING;
            $and = " and ";
            $where[$and . " (status != "] = Application_Model_Order::STATUS_CANCEL;
            $where[")" . $and . " status != "] = Application_Model_Order::STATUS_BANK;
            $where[$and . " dateCreated > "] = $dateinend . " 00:00:00";
            $and = " and ";
            $where[$and . " dateCreated < "] = $dateinend . " 23:59:59";
            $result = Application_Model_Order::getDb()->queryAll($where);
            $i = strtotime($dateinend);
            $arrre[$i]["num"] = count($result);
            $arrre[$i]["ysje"] = 0;
            $arrre[$i]["zyf"] = 0;
            $arrre[$i]["bfyk"] = 0;
            if ($result) {
                foreach ($result as $value) {
                    $arrre[$i]["ysje"] = $arrre[$i]["ysje"] + $value->sum;
                    $arrre[$i]["zyf"] = $arrre[$i]["zyf"] + $value->shipFee;
                    if ($value->status == Application_Model_Order::STATUS_PartBank) {
                        $bftkItem = Application_Model_OrderItem::getByOrderId($value->id);
                        if ($bftkItem) {
                            foreach ($bftkItem as $key => $itemvalue) {
                                if ($itemvalue->status == 1) {
                                    $arrre[$i]["bfyk"] = $arrre[$i]["bfyk"] + ($itemvalue->quantity * $itemvalue->price);
                                }
                            }
                        }
                    }
                }
            }
        }
        if ($dateinend != "" && $dateinbegin != "") {
            $sdate = $dateinbegin <= $dateinend ? $dateinbegin : $dateinend;
            $edate = $dateinbegin >= $dateinend ? $dateinbegin : $dateinend;
            $stime = strtotime($sdate);
            $etime = strtotime($edate);
            for ($i = $stime; $i <= $etime; $i++) {
                $where = "";
                $and = "";
                $where[" status != "] = Application_Model_Order::STATUS_PAYING;
                $and = " and ";
                $where[$and . " (status != "] = Application_Model_Order::STATUS_CANCEL;
                $where[")" . $and . " status != "] = Application_Model_Order::STATUS_BANK;
                $where[$and . " dateCreated > "] = date("Y-m-d H:i:s", $i);
                $where[$and . " dateCreated < "] = date("Y-m-d H:i:s", ($i + 86400));
                $result = Application_Model_Order::getDb()->queryAll($where);
                $arrre[$i]["num"] = count($result);
                $arrre[$i]["ysje"] = 0;
                $arrre[$i]["zyf"] = 0;
                $arrre[$i]["bfyk"] = 0;
                if ($result) {
                    foreach ($result as $value) {
                        $arrre[$i]["ysje"] = $arrre[$i]["ysje"] + $value->sum;
                        $arrre[$i]["zyf"] = $arrre[$i]["zyf"] + $value->shipFee;
                        if ($value->status == Application_Model_Order::STATUS_PartBank) {
                            $bftkItem = Application_Model_OrderItem::getByOrderId($value->id);
                            if ($bftkItem) {
                                foreach ($bftkItem as $key => $itemvalue) {
                                    if ($itemvalue->status == 1) {
                                        $arrre[$i]["bfyk"] = $arrre[$i]["bfyk"] + ($itemvalue->quantity * $itemvalue->price);
                                    }
                                }
                            }
                        }
                    }
                }
                $i+= 86399;
            }
        }
        if ($dateinend == "" && $dateinbegin == "") {
            $arrre = array();
            $nowYm = date("Y-m");
            $nowd = date("d");
            for ($i = 1; $i <= $nowd; $i++) {
                $where = "";
                $and = "";
                $where[" status != "] = Application_Model_Order::STATUS_PAYING;
                $and = " and ";
                $where[$and . " (status != "] = Application_Model_Order::STATUS_CANCEL;
                $where[")" . $and . " status != "] = Application_Model_Order::STATUS_BANK;
                $where[$and . " dateCreated > "] = $nowYm . "-" . $i;
                $where[$and . " dateCreated < "] = $nowYm . "-" . ($i + 1);
                $result = Application_Model_Order::getDb()->queryAll($where);
                $j = strtotime($nowYm . "-" . $i);
                $arrre[$j]["num"] = count($result);
                $arrre[$j]["ysje"] = 0;
                $arrre[$j]["zyf"] = 0;
                $arrre[$j]["bfyk"] = 0;
                if ($result) {
                    foreach ($result as $value) {
                        $arrre[$j]["ysje"] = $arrre[$j]["ysje"] + $value->sum;
                        $arrre[$j]["zyf"] = $arrre[$j]["zyf"] + $value->shipFee;
                        if ($value->status == Application_Model_Order::STATUS_PartBank) {
                            $bftkItem = Application_Model_OrderItem::getByOrderId($value->id);
                            if ($bftkItem) {
                                foreach ($bftkItem as $key => $itemvalue) {
                                    if ($itemvalue->status == 1) {
                                        $arrre[$j]["bfyk"] = $arrre[$j]["bfyk"] + ($itemvalue->quantity * $itemvalue->price);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
//        var_dump($arrre);exit;
        return $arrre;
    }

    public static function bylogistics($logisticsNo) {
        $where[' logisticsNo = '] = $logisticsNo;
        return Application_Model_Order::getDao()->queryOne($where);
    }

    /**
     * 根据物流单号，获取包裹信息
     * @param string $shipNo
     * @return type
     */
    public static function getByShipNo($shipNo) {
        return Application_Model_Order::getDao()->queryOne(array('logisticsNo' => $shipNo));
    }

    /**
     * 根据物流单号，获取包裹信息
     * @param string $shipNo
     * @return type
     */
    public static function getAllByShipNo($shipNo) {
        return self::getDao()->queryAll(array('logisticsNo' => $shipNo));
    }

    /**
     * 获取商品信息
     * @return type
     */
    public function getshipdetail() {
        return Application_Model_OrderItem::getByOrderId($this->_id);
    }

    public function getlogname() {
        if ($this->_logistics) {
            return Application_Model_shipType::load($this->_logistics);
        }
    }

    public static function getStatusList() {
        $statusText = array(
            Application_Model_Order::STATUS_PAYING => "待付款"
            , Application_Model_Order::STATUS_PAID => "已付款"
            , Application_Model_Order::STATUS_CONFRIM => "已受理"
            , Application_Model_Order::STATUS_UNSEND => "已下单"
            , Application_Model_Order::STATUS_SELLER_SENDED => "卖家已发货"
            , Application_Model_Order::STATUS_INSTORE => "已入库"
            , Application_Model_Order::STATUS_SUBSCRIBE => "订单预订"
            , Application_Model_Order::STATUS_CANCEL => "取消"
            , Application_Model_Order::STATUS_BANK => "退货"
            , Application_Model_Order::STATUS_PartBank => "部分退货"
            , Application_Model_Order::STATUS_OUTTIME_UNSEND => "超期未发货"
            , Application_Model_Order::STATUS_OUTTIME_INSTORE => "超期未收货"
            , Application_Model_Order::STATUS_OUTTIME_FIN => "超期财务风险"
            , Application_Model_Order::STATUS_COMPLATED => "完成"
        );
        return $statusText;
    }

    /**
     * 获取客户信息
     * @return type
     */
    public function getbyuserdetail() {
        return Application_Model_User::getByUserId($this->_userId);
    }

    public static function getStatusDescription($status) {
        $statusText = Application_Model_Order::getStatusList();
        $statusStr = $statusText[$status];
        return $statusStr;
    }

    public static function getdumporderdata($OrderSearch) {
        return Application_Model_Order::getDao()->queryAll($OrderSearch->getSearchFileds(), " datePaid desc ");
    }

    /**
     * 根据userid，加载user对象
     * @author wuzw
     * @return type
     */
    public function getuserinfo() {
        if ($this->_userId) {
            return Application_Model_User::load($this->_userId);
        }
    }

    /**
     * 获取分页的数据
     */
    public static function getByPages($orderSearch, $pagesize, $pageindex) {
//        var_dump($orderSearch->getSearchFileds());exit;
//        var_dump($orderSearch->getOrder());exit;
        return Application_Model_Order::getDao()->queryPage($orderSearch->getSearchFileds(), $orderSearch->getOrder(), $pagesize, $pageindex);
    }

    public function getStatusName() {
        if ($this->_status == Application_Model_Order::STATUS_CANCEL) {
            $statusStr = "退款";
            return $statusStr;
        } else {
            return "正常";
        }
    }

    public static function getAllOrder() {
        $where[" (procureNo != "] = "";
        $where[" or procureNo != NULL ) and "] = 1;
        $where[" and (logisticsNo = "] = "";
        $where[" or logisticsNo is NULL ) and "] = 1;
        $where[' and status not in '] = "(" . Application_Model_Order::STATUS_CANCEL . "," . Application_Model_Order::STATUS_BANK . "," . Application_Model_Order::STATUS_INSTORE . ")";
        $where[' and isdelete != '] = 1;
        return Application_Model_Order::getDao()->queryAll($where);
    }

    public static function getDateByOrder($stime, $etime) {
        if ($stime != null) {
            $where[' dateCreated >='] = $stime;
        } else {
            $where[' dateCreated >='] = date('Y-m-d');
        }
        if ($etime != null) {
            $where[' and dateCreated <='] = $etime . " 23:59:59";
        }
        $where[" and status not in "] = "(" . Application_Model_Order::STATUS_CANCEL . "," . Application_Model_Order::STATUS_PartBank . "," . Application_Model_Order::STATUS_BANK . "," . Application_Model_Order::STATUS_PAYING . ")";
        return Application_Model_Order::getDao()->queryAll($where);
    }

    public static function ByDateOrder($stime, $etime) {
        if ($stime != null) {
            $where[' dateCreated >='] = $stime;
        } else {
            $where[' dateCreated >='] = date('Y-m-d');
        }
        if ($etime != null) {
            $where[' and dateCreated <='] = $etime . " 23:59:59";
        }
        $where[" and status not in "] = "(" . Application_Model_Order::STATUS_CANCEL . "," . Application_Model_Order::STATUS_PartBank . "," . Application_Model_Order::STATUS_BANK . "," . Application_Model_Order::STATUS_PAYING . ")";
        return Application_Model_Order::getDao()->distinct($where, "procureNo");
    }

    /**
     * 受理
     * @param type $operator 操作人
     */
    public function SetConfrim($operator) {
        $this->_status = self::STATUS_CONFRIM;
        $this->_operator = $operator;
        $this->_dateConfrim = date("Y-m-d H:i:s");
        $this->save();
        Application_Model_Operate::addOperate(0, null, $this->_id, "代购订单受理", $this->_userId);
        Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $this->_id, $operator, $this->getStatusNames(), Application_Model_Tracking::User_Block, $this->_status, date("Y-m-d H:i:s"));
        $orderItem = $this->getItems();
        foreach ($orderItem as $orVal) {
            $orVal->taoBaoUrl = $orVal->getTaobaoTopUrl();
            $orVal->save();
        }
    }

    /**
     * 设为已下单
     * @param type $operator
     * @return int 2 下单号不能为空 1 为成功下单 
     */
    public function SetWaitShip() {
        if ($this->_procureNo == null) {
            return 2;
        }
        $this->_status = self::STATUS_UNSEND;
        $this->_dateConfrim = date("Y-m-d H:i:s");
        $this->save();
        $userItem = Application_Model_UserAccount::addAccount($this->_userId);
        $comment = "代购订单受理";
        $userItem->MoneyExchangeScore(Application_Model_UserAccount::ExchangeScore_Oreder, $this->_sum, $comment);
        Application_Model_Operate::addOperate($this->_sum, null, $this->_id, "代购订单下单", $this->_userId);
        Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $this->_id, $this->_operator, $this->getStatusNames(), Application_Model_Tracking::User_Block, $this->_status, date("Y-m-d H:i:s"));
        return 1;
    }

    /**
     * 更新订单号
     * @param type $procureNo 订单号
     */
    public function UpdateProcureNo($procureNo) {
        if ($procureNo == "") {
            return 2;
        }
        $isTrue = self::getIsTrueByIdProcureNo($this->_id, $procureNo);
        if ($isTrue) {
            return 3;
        }
        $this->_procureNo = $procureNo;
        $this->_dateConfrim = date("Y-m-d H:i:s");
        $this->save();
        Application_Model_Operate::addOperate(0, null, $this->_id, "更新代购订单号：".$procureNo, $this->_userId);
        Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $this->_id, $this->_operator, "更新代购订单号", Application_Model_Tracking::User_Block, "更新订单号", date("Y-m-d H:i:s"));
        return 1;
    }

    /**
     * 更新物流信息
     * @param type $procureNo 订单号
     * @param type $logistics 物流公司
     * @param type $logisticsNo 物流单号
     */
    public function UpdateLogistics($procureNo, $logistics, $logisticsNo) {
        $result_one = $this->UpdateProcureNo($procureNo);
        if ($result_one > 1) {
            return $result_one;
        }
        $orderItem = self::bylogistics($logisticsNo);
        if ($orderItem && $orderItem->id != $this->_id) {
            return 4;
        }
        $this->_logistics = $logistics;
        $this->_logisticsNo = $logisticsNo;
        $this->_dateConfrim = date("Y-m-d H:i:s");
        $this->_consignTime = $this->_consignTime ? $this->_consignTime : date("Y-m-d H:i:s");
        $this->save();
        Application_Model_Operate::addOperate(0, null, $this->_id, "更新代购物流信息：".$logisticsNo, $this->_userId);
        Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $this->_id, $this->_operator, "更新订单物流信息", Application_Model_Tracking::User_Block, "更新物流信息", date("Y-m-d H:i:s"));
        return 1;
    }

    public function SetSeller() {
        if ($this->_status != self::STATUS_UNSEND && $this->_status != self::STATUS_OUTTIME_UNSEND && $this->_status != self::STATUS_SUBSCRIBE) {
            return 3;
        }
        if ($this->_logisticsNo == "") {
            return 2;
        }
        $this->_status = self::STATUS_SELLER_SENDED;
        $this->_dateConfrim = date("Y-m-d H:i:s");
        $this->save();
        Application_Model_Operate::addOperate(0, null, $this->_id, "代购设置卖家已发货", $this->_userId);
        Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $this->_id, $this->_operator, $this->getStatusNames(), Application_Model_Tracking::User_Block, $this->_status, date("Y-m-d H:i:s"));
        return 1;
    }

    private $_TaoBaoItem;

    /**
     * 通过下单订单号获取是哪个账号下单的
     * @return type
     */
    public function getTaoBao() {
        if ($this->_TaoBaoItem == null) {
            if ($this->_procureNo) {
                $taobaoSign = substr($this->_procureNo, -4);
                $this->_TaoBaoItem = Application_Model_Taobaoapi::getByTaoBaoSign($taobaoSign);
            }
        }
        return $this->_TaoBaoItem;
    }

    /**
     * 获取$status状态下的代购
     * @param type $status
     * @return type
     */
    public static function getOrderAllByStatus($status) {
        return self::getDao()->queryAll(array("status" => $status, " and isdelete != " => 1));
    }

    /**
     * 设置已入库 1为入库 2为没有入库
     */
    public function setInStore() {
        if ($this->_status != self::STATUS_SELLER_SENDED && $this->_status != self::STATUS_OUTTIME_INSTORE && $this->_status != self::STATUS_OUTTIME_FIN) {
            return 3;
        }
//        $storeItem = Application_Model_StoreItem::getbyLogistics($this->_logisticsNo);
//        if(!$storeItem){
//            return 2;
//        }
        $this->ActivityConsumeExchangeScore();
        $this->_status = self::STATUS_INSTORE;
        $this->_dateInStore = date("Y-m-d H:i:s");
        $this->_dateConfrim = date("Y-m-d H:i:s");
        $this->save();
        Application_Model_Operate::addOperate(0, null, $this->_id, "代购设置已入库", $this->_userId);
        Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $this->_id, $this->_operator, $this->getStatusNames(), Application_Model_Tracking::User_Block, $this->_status, date("Y-m-d H:i:s"));
        return 1;
    }

    public function getStoreBylogistics() {
        return Application_Model_StoreItem::getAllbyLogistics($this->_logisticsNo);
    }

    public function getIsInStore() {
        $storeItem = $this->getStoreBylogistics();
        if (!$storeItem) {
            return true;
        }
        foreach ($storeItem as $storeVal) {
            if ($storeVal->isdelete == 1 || $storeVal->userid != $this->_userId) {
                continue;
            }
            return false;
        }
        return true;
    }

    public static function ByProcureNo($procureNo) {
        $where[" procureNo = "] = $procureNo;
        $item = self::getDao()->queryAll($where);
        $rearr = array("sum" => 0, "shipFee" => 0);
        foreach ($item as $value) {
            $rearr["sum"] += $value->Sum;
        }
        $rearr["shipFee"] += $value->ShipFee;
        return $rearr;
    }

    /**
     * 检查传入的拆分字符串格式是否正确
     * @param type $itemList
     * @return null 格式错误 | array 格式正确，返回下一步所需数据格式
     */
    private function AnalysisItemList($itemList) {
        $arrItemId = explode(",", trim($itemList, ','));
        $return = array();

        foreach ($arrItemId as $item) {
            if ($item == '') {
                return null;
            }
            $arrOrderNum = explode(":", $item);
            if (count($arrOrderNum) != 2 || $arrOrderNum[0] == '' || $arrOrderNum[0] <= 0 || $arrOrderNum[1] == '' || $arrOrderNum[1] < 0) {
                return null;
            }
            $return[$arrOrderNum[0]] = $arrOrderNum[1];
        }
        return $return;
    }

    /**
     * 检查拆分商品的数量是否在符合规范中
     * @param type $productArray
     * @return null 数量不符 | $money 数据符合，并返回拆分商品的总额
     */
    private function AnalysisItem($productArray) {
        $splitSum = 0;
        $money = 0;
        foreach ($productArray as $orderItmeId => $quantity) {
            $orderItem = Application_Model_OrderItem::load($orderItmeId);
            if ($orderItem == null) {
                return null;
            }
            if ($orderItem->Status == Application_Model_OrderItem::Status_Refund || $quantity > $orderItem->quantity) {
                return null;
            }

            $money += $orderItem->Price * $quantity;
            $splitSum += $quantity;
        }

        $sum = 0;
        foreach ($this->getItems() as $itemVal) {
            if ($itemVal->Status != 1) {
                $sum = $sum + $itemVal->quantity;
            }
        }

        if ($splitSum <= 0 || $splitSum == $sum) {
            return null;
        }
        return $money;
    }

    public function getItemInfo($idlist) {
        $arrItemId = explode(",", trim($idlist, ','));
        $return = array();
        foreach ($arrItemId as $key => $itemId) {
            if ($itemId == '') {
                return 0;
            }
            $orderItem = Application_Model_OrderItem::load($itemId);
            if ($orderItem == null) {
                return 0;
            }
            if ($orderItem->Status == Application_Model_OrderItem::Status_Refund) {
                return 2;
            }
            if ($this->_id != $orderItem->OrderId) {
                return 3;
            }
            $productd = $orderItem->byproductd;
            $image = $productd->image ? $productd->image : $productd->remoteImage;
            $arrimage = explode('"', $image);
            if (count($arrimage) > 1) {
                $imgUrl = $arrimage[1];
            } else {
                $imgUrl = $image;
            }
            $return[$key]["id"] = $orderItem->Id;
            $return[$key]["name"] = $orderItem->ProductName;
            $return[$key]["alias"] = $productd->PropertyAlias;
            $return[$key]["num"] = $orderItem->quantity;
            $return[$key]["img"] = $imgUrl;
        }
        return $return;
    }

    /**
     * 拆分
     * @param type $itemList
     * @param type $item
     * @return int
     */
    public function SplitOrder($itemList) {
        if ($this->_status == self::STATUS_PAYING || $this->_status == self::STATUS_CANCEL || $this->_status == self::STATUS_BANK) {
            return 2;
        }

        $productArray = $this->AnalysisItemList($itemList);
        if ($productArray == null) {
            return 4;
        }
        $money = $this->AnalysisItem($productArray);
        if ($money == null) {
            return 3;
        }

        $newDiscount = 0;
        $oldDiscount = 0;
        $couponItem = false;
        $newCouponItem = false;
        if ($this->_discount > 0) {
            //获取原订单的优惠券信息
            $couponSearch = new Application_Model_Filter_CouponSearch();
            $couponSearch->userId = $this->_userId;
            $couponSearch->useType = Application_Model_Coupon::useType_Order;
            $couponSearch->relevance = $this->_id;
            $couponSearch->status = Application_Model_Coupon::STATUS_USED;
            $couponItem = Application_Model_Coupon::getOne($couponSearch);

            if (($this->_sum - $money) >= $this->_discount) {
                $oldDiscount = 0;
                $newDiscount = $this->_discount;
            } else if (($this->_sum - $money) < $this->_discount && $money >= $this->_discount) {
                $oldDiscount = $this->_discount;
                $newDiscount = 0;
            } else {
                $oldDiscount = $money;
                $newDiscount = $this->_discount - $money;
                $newCouponItem = Application_Model_Coupon::addCoupon($this->_userId, $couponItem->dateExpired, null, $newDiscount, $newDiscount, null, Application_Model_Coupon::Type_SatisfyReduce, Application_Model_Coupon::Scope_All, $couponItem->startTime, $couponItem->batchNo, $couponItem->name);
            }
        }
        $orderItem = new Application_Model_Order();
        $orderItem->DateCreated = $this->_dateCreated;
        $orderItem->ShipFee = 0;
        $orderItem->ProductTotal = $money;
        $orderItem->Sum = $money;
        $orderItem->Status = self::STATUS_CONFRIM;
        $orderItem->UserId = $this->_userId;
        $orderItem->Comment = $this->_comment;
        $orderItem->DatePaid = $this->_datePaid;
        $orderItem->Operator = $this->_operator;
        $orderItem->dateCancel = $this->_dateCancel;
        $orderItem->Problem = self::Problem_Default;
        $orderItem->isAbnormal = self::Abnormal_Default;
        $orderItem->Isdelete = 0;
        $orderItem->CkPass = 0;
        $orderItem->Scheme = 0;
        $orderItem->Discount = $oldDiscount;
        $orderItem->save();
        $user = Application_Model_User::load($this->_userId);
        $userdetail = Application_Model_UserAccount::load($this->_userId);
        $beforeMoney = $userdetail->money;
        $financeData = array(
            'transaction_number' => '',
            'trader' => 'backend-account-cr',
            'customer_id' => $orderItem->userId,
            'member' => 'admin',
            'amount' => $money,
            'currency' => 'CNY',
            'customer_name' => $user->nikename,
            'rate' => '1',
            'rate_amount' => '0',
            'period_start' => $beforeMoney,
            'period_end' => $beforeMoney,
            'business_type' => 'chaifendingdan',
            'order_sn' => $this->getOrderNum(),
            'remark' => '',
            'created_at' => date('Y-m-d H:i:s')
        );
        
        $this->_addFinance($userdetail,$financeData);
        $financeData['trader'] = 'account-number-dr';
        $this->_addFinance($userdetail,$financeData);
        $financeData['trader'] = 'account-number-cr';
        $financeData['business_type'] = 'spzz';
        $financeData['order_sn'] = $orderItem->getOrderNum();
        $this->_addFinance($userdetail,$financeData);
        $financeData['trader'] = 'backend-account-dr';
        $this->_addFinance($userdetail,$financeData);
        
        if($oldDiscount > 0){
            $financeData['amount'] = $this->_discount - $newDiscount;
            $financeData['trader'] = 'backend-account-cr';
            $financeData['business_type'] = 'dg-discount';
            $financeData['order_sn'] = $this->getOrderNum();
            $this->_addFinance($userdetail,$financeData);
            $financeData['trader'] = 'account-number-dr';
            $this->_addFinance($userdetail,$financeData);
            $financeData['trader'] = 'account-number-cr';
            $financeData['order_sn'] = $orderItem->getOrderNum();
            $this->_addFinance($userdetail,$financeData);
            $financeData['trader'] = 'backend-account-dr';
            $this->_addFinance($userdetail,$financeData);
        }
        
        if ($couponItem && $orderItem->Discount > 0) {
            $couponItem->relevance = $orderItem->Id;
            $couponItem->Discount = $orderItem->Discount;
            $couponItem->Money = $orderItem->Discount;
            $couponItem->save();
        }

        foreach ($productArray as $orderItmeId => $quantity) {
//            $item = Application_Model_OrderItem::load($orderItmeId);
            $item = Uuch_Util::first($this->getItems(), function($item) use($orderItmeId) {
                        return $item->Id == $orderItmeId;
                    });
            if ($quantity == 0) {
                continue;
            }
            if ($item->Quantity == $quantity) {
                $item->OrderId = $orderItem->Id;

                $item->save();
                continue;
            }
            $item->Quantity = $item->Quantity - $quantity;
            $item->save();
            $newitem = new Application_Model_OrderItem();
            $newitem->Price = $item->Price;
            $newitem->ProductName = $item->ProductName;
            $newitem->Quantity = $quantity;
            $newitem->ProductId = $item->ProductId;
            $newitem->OrderId = $orderItem->Id;
            $newitem->Comment = $item->Comment;
            $newitem->Sku = $item->Sku;
            $newitem->Status = $item->Status;
            $newitem->Description = $item->Description;
            $newitem->TaoBaoUrl = $item->TaoBaoUrl;
            $newitem->ProblemContent = "";
            $newitem->CkPass = 0;
            $newitem->save();
        }
        $comment = "订单：" . $this->getOrderNum() . "拆分成(" . $this->getOrderNum() . "," . $orderItem->getOrderNum() . ")";
        $this->_productTotal = $this->_productTotal - $money;
        $this->_sum = $this->_sum - $money;
        $this->_dateConfrim = date("Y-m-d H:i:s");
        $this->_discount = $newDiscount;
        $this->saveSelf();

        if ($newCouponItem && $this->_discount > 0) {
            $newCouponItem->status = Application_Model_Coupon::STATUS_USED;
            $newCouponItem->useTime = $this->_dateCreated;
            $newCouponItem->useType = Application_Model_Coupon::useType_Order;
            $newCouponItem->relevance = $this->_id;
            $newCouponItem->Discount = $this->_discount;
            $newCouponItem->Money = $this->_discount;
            $newCouponItem->save();
        }
        Application_Model_Operate::addOperate(0, null, $this->_id, $comment, $this->_userId);
        Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $orderItem->id, $orderItem->operator, $comment, Application_Model_Tracking::User_Block, Application_Model_Tracking::Type_Split, date("Y-m-d H:i:s"));
        Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $this->_id, $this->_operator, $comment, Application_Model_Tracking::User_Block, Application_Model_Tracking::Type_Split, date("Y-m-d H:i:s"));
        $orderPath = Application_Model_PathLevel::bySubId($this->_id);
        $path = ($orderPath ? $orderPath->Path : $this->_id) . "/" . $this->_id;
        $level = $orderPath ? $orderPath->Level + 1 : 1;
        Application_Model_PathLevel::addPathLevel(Application_Model_DomainobjectType::ObjectType_Order, $this->_id, $this->_id, $path, $level);
        $newOrderPath = Application_Model_PathLevel::bySubId($orderItem->id);
        $newPath = ($newOrderPath ? $newOrderPath->Path : $this->_id) . "/" . $orderItem->id;
        $newLevel = $newOrderPath ? $newOrderPath->Level + 1 : 1;
        Application_Model_PathLevel::addPathLevel(Application_Model_DomainobjectType::ObjectType_Order, $this->_id, $orderItem->id, $newPath, $newLevel);
        return 1;
    }

    protected function _addFinance($account, $data) {
        require_once(APPLICATION_PATH . '/../library/finance/General.php');
        $api = new General($data['amount'], $account);
        $api->setFields($data);
        $api->addTransaction();
    }
    /**
     * 代购预定
     * @param type $reserveTime
     * @param type $reserveCause
     * @return int
     */
    public function setReserveOrder($reserveTime, $reserveCause) {
        if ($this->_status != self::STATUS_CONFRIM && $this->_status != self::STATUS_UNSEND && $this->_status != self::STATUS_OUTTIME_UNSEND) {
            return 2;
        }
        $this->_dateShip = $reserveTime;
        $this->_dateConfrim = date("Y-m-d H:i:s");
        $this->_status = Application_Model_Order::STATUS_SUBSCRIBE;
        $this->save();
        Application_Model_Operate::addOperate(0, null, $this->_id, "代购预定发货时间为：".$this->_dateShip, $this->_userId);
        Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $this->_id, $this->_operator, "订单：" . $this->getOrderNum() . "因(" . $reserveCause . ")，预计" . $reserveTime . "发货。", Application_Model_Tracking::User_Block, $this->_status, date("Y-m-d H:i:s"));
        return 1;
    }

    /**
     * 修改状态
     * @param type $status
     * @param type $operator
     * @return int
     */
    public function editInterior($status, $operator) {
        if ($this->_status == self::STATUS_CANCEL || $this->_status == self::STATUS_PAYING) {
            return 2;
        }
        if ($status == self::STATUS_CONFRIM) {
            $this->_procureNo = "";
            $this->_logistics = "";
            $this->_logisticsNo = "";
        }

        if ($status == self::STATUS_UNSEND || $status == self::STATUS_OUTTIME_UNSEND) {
            $this->_logistics = "";
            $this->_logisticsNo = "";
        }
        $statusName = $this->getStatusNames();
        $this->_status = $status;
        $this->_dateConfrim = date("Y-m-d H:i:s");
        $this->save();
        Application_Model_Operate::addOperate(0, null, $this->_id, "代购状态修改为：".$this->getStatusNames(), $this->_userId);
        Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $this->_id, $operator, "订单：" . $this->getOrderNum() . "由(" . $statusName . ")改成（" . $this->getStatusNames() . "）。", Application_Model_Tracking::User_None, $this->_status, date("Y-m-d H:i:s"));
        return 1;
    }

    private function canRefoundMoney() {
        foreach ($this->getItems() as $item) {
            if ($item->status != Application_Model_OrderItem::Status_Refund) {
                return TRUE;
            }
        }
        return false;
    }

    /**
     * 取消
     * @param type $operator
     * @return int
     */
    public function Cancel($operator) {
        if ($this->_status == self::STATUS_INSTORE || $this->_status == self::STATUS_CANCEL) {
            return 2;
        }
        $this->_status = self::STATUS_CANCEL;
        if ($this->_problem == self::Problem_Appear) {
            $this->_problem = self::Problem_Complete;
        }
        $this->_dateCancel = date("Y-m-d H:i:s");
        $this->_dateConfrim = date("Y-m-d H:i:s");
        $accountObj = Application_Model_UserAccount::load($this->_userId);
        $itemmoney = 0;
        $arrup = array();
        $couponItem = false;
        try {
            $db = Application_Model_OrderItem::getDao();
            $db->beginTran();
            $this->save();
            if (!$this->canRefoundMoney()) {
                $db->commit();
                return 1;
            }
            if ($this->_discount > 0) {
                $couponSearch = new Application_Model_Filter_CouponSearch();
                $couponSearch->userId = $this->_userId;
                $couponSearch->useType = Application_Model_Coupon::useType_Order;
                $couponSearch->relevance = $this->_id;
                $couponSearch->status = Application_Model_Coupon::STATUS_USED;
                $couponItem = Application_Model_Coupon::getOne($couponSearch);
            }
            foreach ($this->getItems() as $item) {
                if ($item->status == 1) {
                    continue;
                }
                $item->status = 1;
                $item->save();
                $itemmoney = $itemmoney + ($item->price * $item->quantity);
                $arrup[$item->id] = $item->price;
            }
            $shipFee = (float) ($this->_shipFee);
            if ($shipFee > 0) {
                $itemmoney = $itemmoney + $shipFee;
            }
            if ($couponItem) {
                $itemmoney = $itemmoney - $this->_discount;
                $couponItem->status = Application_Model_Coupon::STATUS_OK;
                $couponItem->useTime = null;
                $couponItem->relevance = null;
                $couponItem->useType = Application_Model_Coupon::useType_Default;
                $couponItem->save();
                $this->_discount = 0;
                $this->saveSelf();
            }
            $beforeMoney = $accountObj->money;
            $accountObj->money = $accountObj->money + $itemmoney;
            $accountObj->save();
            $comment = "代购订单:" . $this->getOrderNum() . '(包含运费)全部退款';
            $afterMoney = $beforeMoney + $itemmoney;
            $userAccountHistory = new Application_Model_UserAccountHistory();
            $userAccountHistory->type = Application_Model_UserAccountHistory::TYPE_RETURNMONEY;
            $userAccountHistory->beforeMoney = $beforeMoney;
            $userAccountHistory->afterMoney = $afterMoney;
            $userAccountHistory->comment = $comment;
            $userAccountHistory->dateCreated = date('Y-m-d H:i:s', time());
            $userAccountHistory->relaseId = $this->_id;
            $userAccountHistory->accountId = $this->_userId;
            $userAccountHistory->State = Application_Model_UserAccountHistory::STATE_MONEY;
            $userAccountHistory->save();
            Application_Model_Operate::addOperate(0, null, $this->_id, $comment, $this->_userId);
            Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $this->_id, $operator, $comment, Application_Model_Tracking::User_Block, $this->_status, date("Y-m-d H:i:s"));
            $db->commit();
        } catch (Exception $exc) {
            $db->rollBack();
            return 0;
        }
        return $arrup;
    }

    private function AnalysisOrderItem() {
        foreach ($this->getItems() as $itemVal) {
            if ($itemVal->Status != Application_Model_OrderItem::Status_Refund) {
                return true;
            }
        }
        $this->_status = self::STATUS_CANCEL;
        if ($this->_problem == self::Problem_Appear) {
            $this->_problem = self::Problem_Complete;
        }
        $this->saveSelf();
        return false;
    }

    /**
     * 单项退款
     * @param type $singleId
     * @param type $operator
     * @return int
     */
    public function singleReturn($singleId, $operator) {
        if ($this->_status == self::STATUS_INSTORE || $this->_status == self::STATUS_CANCEL) {
            return 2;
        }
        $this->_dateConfrim = date("Y-m-d H:i:s");
        $accountObj = Application_Model_UserAccount::load($this->_userId);
        try {
            $db = Application_Model_OrderItem::getDao();
            $db->beginTran();
            $couponItem = false;

            $item = Application_Model_OrderItem::load($singleId);
            if ($item->status == Application_Model_OrderItem::Status_Refund || $item->OrderId != $this->_id) {
                return 3;
            }
            $this->saveSelf();
            $item->status = Application_Model_OrderItem::Status_Refund;
            $item->save();
            $itemmoney = ($item->price * $item->quantity);
            if ($this->_discount > 0) {
                $couponSearch = new Application_Model_Filter_CouponSearch();
                $couponSearch->userId = $this->_userId;
                $couponSearch->useType = Application_Model_Coupon::useType_Order;
                $couponSearch->relevance = $this->_id;
                $couponSearch->status = Application_Model_Coupon::STATUS_USED;
                $couponItem = Application_Model_Coupon::getOne($couponSearch);
            }
            $newDiscount = 0;
            if ($this->AnalysisOrderItem()) {
                $shipFee = 0;
                $comment = "代购订单:" . $this->getOrderNum() . '中的商品' . mb_substr($item->productName, 0, 8, 'utf-8') . '···单项退款';
                if ($couponItem && $this->_discount >= $itemmoney) {
                    Application_Model_Coupon::addCoupon($this->_userId, $couponItem->dateExpired, null, $itemmoney, $itemmoney, null, Application_Model_Coupon::Type_SatisfyReduce, Application_Model_Coupon::Scope_All, $couponItem->startTime, $couponItem->batchNo, $couponItem->name);
                    $newDiscount = ($this->_discount - $itemmoney);
                    $couponItem->discount = $newDiscount;
                    $couponItem->money = $newDiscount;
                    $couponItem->save();
                    $this->_discount = $newDiscount;
                    $this->saveSelf();
                    $db->commit();
                    return 1;
                } else if ($couponItem && $this->_discount < $itemmoney) {
                    $couponItem->discount = $this->_discount;
                    $couponItem->money = $this->_discount;
                    $couponItem->status = Application_Model_Coupon::STATUS_OK;
                    $couponItem->useTime = null;
                    $couponItem->relevance = null;
                    $couponItem->useType = Application_Model_Coupon::useType_Default;
                    $couponItem->save();
                    $itemmoney = ($itemmoney - $this->_discount);
                    $this->_discount = 0;
                    $this->saveSelf();
                }
            } else {
                $shipFee = (int) ($this->_shipFee);
                $comment = "代购订单:" . $this->getOrderNum() . '(包含运费)全部退款';
                if ($couponItem) {
                    $couponItem->status = Application_Model_Coupon::STATUS_OK;
                    $couponItem->useTime = null;
                    $couponItem->relevance = null;
                    $couponItem->useType = Application_Model_Coupon::useType_Default;
                    $couponItem->save();
                    $itemmoney = $itemmoney - $this->_discount;
                    $this->_discount = 0;
                    $this->saveSelf();
                }
            }
            if ($shipFee > 0) {
                $itemmoney = $itemmoney + $shipFee;
            }
            $beforeMoney = $accountObj->money;
            $accountObj->money = $accountObj->money + $itemmoney;
            $accountObj->save();

            $afterMoney = $beforeMoney + $itemmoney;
            $userAccountHistory = new Application_Model_UserAccountHistory();
            $userAccountHistory->type = Application_Model_UserAccountHistory::TYPE_RETURNMONEY;
            $userAccountHistory->beforeMoney = $beforeMoney;
            $userAccountHistory->afterMoney = $afterMoney;
            $userAccountHistory->comment = $comment;
            $userAccountHistory->dateCreated = date('Y-m-d H:i:s', time());
            $userAccountHistory->relaseId = $this->_id;
            $userAccountHistory->accountId = $this->_userId;
            $userAccountHistory->State = Application_Model_UserAccountHistory::STATE_MONEY;
            $userAccountHistory->save();
            Application_Model_Operate::addOperate(0, null, $this->_id, $comment, $this->_userId);
            Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $this->_id, $operator, $comment, Application_Model_Tracking::User_Block, $this->_status, date("Y-m-d H:i:s"));

            $db->commit();
        } catch (Exception $exc) {
            $db->rollBack();
            return 0;
        }
        return 1;
    }

    private function AnalysisMergerOrder($arrItemId) {
        for ($index = 0; $index < count($arrItemId); $index++) {
            if ($arrItemId[$index] == "") {
                continue;
            }
            $orderItemX = Application_Model_Order::load($arrItemId[$index]);
            if ($orderItemX->UserId != $this->_userId) { //不是同一用户的
                return 3;
            }
//            if($orderItemX->Status != self::STATUS_CONFRIM){ //状态不是已受理的
//                return 2;
//            }
            if ($orderItemX->Isdelete == 1) { //订单是已经删除的
                return 5;
            }
        }
        return 1;
    }

    /**
     * 合并
     * @param type $arrItemId
     * @param type $operator
     * @return int
     */
    public function MergerOrder($arrItemId, $operator) {
        $productTotal = 0;
        $shipFee = 0;
        $sum = 0;
        $analysis = $this->AnalysisMergerOrder($arrItemId);
        if ($analysis > 1) {
            return $analysis;
        }
        $couponItem = false;
        $newDiscount = 0;
        for ($index = 0; $index < count($arrItemId); $index++) {
            if ($arrItemId[$index] == "") {
                continue;
            }
            $orderItemX = Application_Model_Order::load($arrItemId[$index]);
            if (!$couponItem) {
                $couponSearch = new Application_Model_Filter_CouponSearch();
                $couponSearch->userId = $orderItemX->UserId;
                $couponSearch->useType = Application_Model_Coupon::useType_Order;
                $couponSearch->relevance = $orderItemX->Id;
                $couponSearch->status = Application_Model_Coupon::STATUS_USED;
                $couponItem = Application_Model_Coupon::getOne($couponSearch);
            }
            $productTotal += $orderItemX->ProductTotal;
            $shipFee += $orderItemX->ShipFee;
            $sum += $orderItemX->Sum;
            $newDiscount += $orderItemX->Discount;
        }
        $newOrder = new Application_Model_Order();
        $newOrder->DateConfrim = $this->_dateConfrim;
        $newOrder->DateCreated = $this->_dateCreated;
        $newOrder->DateInStore = $this->_dateInStore;
        $newOrder->Status = $this->_status;
        $newOrder->UserId = $this->_userId;
        $newOrder->Comment = $this->_comment;
        $newOrder->ParentId = $this->_parentId;
        $newOrder->ShopId = $this->_shopId;
        $newOrder->ProcureNo = $this->_procureNo;
        $newOrder->DateProcure = $this->_dateProcure;
        $newOrder->Logistics = $this->_logistics;
        $newOrder->LogisticsNo = $this->_logisticsNo;
        $newOrder->ProblemContent = $this->_problemContent;
        $newOrder->CkPass = $this->_ckPass;
        $newOrder->Scheme = 0;
        $newOrder->DatePaid = $this->_datePaid;
        $newOrder->Operator = $this->_operator;
        $newOrder->DateShip = $this->_dateShip;
        $newOrder->Problem = $this->_problem;
        $newOrder->ProductTotal = $productTotal;
        $newOrder->ShipFee = $shipFee;
        $newOrder->Sum = $sum;
        $newOrder->Isdelete = 0;
        $newOrder->Discount = $newDiscount;
        $newOrder->save();
        if ($couponItem && $newOrder->Discount > 0) {
            $newCouponItem = Application_Model_Coupon::addCoupon($this->_userId, $couponItem->dateExpired, null, $newDiscount, $newDiscount, null, Application_Model_Coupon::Type_SatisfyReduce, $couponItem->Scope, $couponItem->startTime, $couponItem->batchNo, $couponItem->name);
            $newCouponItem->status = Application_Model_Coupon::STATUS_USED;
            $newCouponItem->useTime = $newOrder->DateCreated;
            $newCouponItem->useType = Application_Model_Coupon::useType_Order;
            $newCouponItem->relevance = $newOrder->Id;
            $newCouponItem->save();
        }
        $oldOrder = "";
        for ($index = 0; $index < count($arrItemId); $index++) {
            if ($arrItemId[$index] == "") {
                continue;
            }
            $itemX = Application_Model_OrderItem::getByOrderId($arrItemId[$index]);
            foreach ($itemX as $xVal) {
                $newItem = new Application_Model_OrderItem();
                $newItem->Price = $xVal->Price;
                $newItem->ProductName = $xVal->ProductName;
                $newItem->Quantity = $xVal->Quantity;
                $newItem->ProductId = $xVal->ProductId;
                $newItem->Comment = $xVal->Comment;
                $newItem->Sku = $xVal->Sku;
                $newItem->Status = $xVal->Status;
                $newItem->Description = $xVal->Description;
                $newItem->TaoBaoUrl = $xVal->TaoBaoUrl;
                $newItem->ProblemContent = $xVal->ProblemContent;
                $newItem->CkPass = $xVal->CkPass;
                $newItem->OrderId = $newOrder->Id;
                $newItem->save();
            }
            $orderItemX = Application_Model_Order::load($arrItemId[$index]);
            $orderItemX->Isdelete = 1;
            $oldOrder .= $orderItemX->getOrderNum() . ",";
            $orderItemX->save();

            Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $orderItemX->Id, $operator, "代购订单（" . $oldOrder . "）合并成一个新代购订单：" . $newOrder->getOrderNum(), Application_Model_Tracking::User_Block, "", date("Y-m-d H:i:s"));
        }
        Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $newOrder->Id, $operator, "代购订单（" . $oldOrder . "）合并成一个新代购订单：" . $newOrder->getOrderNum(), Application_Model_Tracking::User_Block, "", date("Y-m-d H:i:s"));
        Application_Model_Operate::addOperate(0, null, $this->_id, "代购订单（" . $oldOrder . "）合并成一个新代购订单：" . $newOrder->getOrderNum(), $this->_userId);
        return 1;
    }

    public function getIsProblem() {
        return Application_Model_problem::byOneissue($this->_id, Application_Model_problem::TYPE_ORDER);
    }

    public static function getIsTrueByIdProcureNo($id, $procureNo) {
        $countAll = self::getDao()->queryAll(array("procureNo = " => $procureNo));
        $countnum = count($countAll);
        if ($countnum == 1) {
            if ($countAll[0]->Id != $id) {
                return true;
            }
        }
        if ($countnum > 1) {
            return true;
        }
        return false;
    }

    public function getReverseStatus() {
        $arrre = array();
        if ($this->_isdelete != 1) {
            switch ($this->_status) {
                case self::STATUS_PAID:
                    $arrre = array("fun" => "SetConfrim", "name" => "设为已受理");
                    break;
                case self::STATUS_CONFRIM:
                    $arrre = array("fun" => "SetWaitShip", "name" => "设为已下单");
                    break;
                case self::STATUS_UNSEND:
                case self::STATUS_OUTTIME_UNSEND:
                case self::STATUS_SUBSCRIBE:
                    $arrre = array("fun" => "SetSeller", "name" => "设为卖家已发货");
                    break;
                case Application_Model_Order::STATUS_SELLER_SENDED:
                case Application_Model_Order::STATUS_OUTTIME_INSTORE:
                case Application_Model_Order::STATUS_OUTTIME_FIN:
                    $arrre = array("fun" => "SetInStore", "name" => "设为已入库");
                    break;
                default :
                    $arrre = array("fun" => "", "name" => "");
                    break;
            }
        } else {
            $arrre = array("fun" => "isdel", "name" => "已删除");
        }
        return $arrre;
    }

    /**
     *  获取代购数量
     */
    public function getSunOrder() {
        $num = 0;
        foreach ($this->getItems() as $value) {
            if ($value->status == Application_Model_OrderItem::Status_Refund) {
                continue;
            }
            $num = $num + $value->quantity;
        }
        return $num;
    }

    /**
     * 设置问题
     * @param type $content
     * @return type
     */
    public function addProblem($content) {
        $this->_problem = self::Problem_Appear;
        $this->_dateConfrim = date("Y-m-d H:i:s");
        $this->save();
        $title = "代购订单(" . $this->getOrderNum() . ")出现问题。";
        $type = Application_Model_problem::TYPE_ORDER;
        $issuetype = Application_Model_problem::SUE_YOUQI;
        Application_Model_problem::addProblem($this->_userId, $this->_id, $type, $issuetype, $title, $content);
        $messageItem = new Application_Model_Mail();
        $messageItem->title = "尊敬的客户，您好！您的" . $title;
        $messageItem->userId = $this->_userId;
        $messageItem->type = 2;
        $messageItem->status = 0;
        $messageItem->message = $content;
        $messageItem->dateCreated = date("Y-m-d H:i:s");
        $messageItem->save();
        $userItem = Application_Model_User::load($this->_userId);
        Application_Model_Email::sendMail($this->_userId, $userItem->email, "尊敬的客户，您好！您的" . $title, $content);
        Application_Model_Operate::addOperate(0, null, $this->_id, "代购订单设置问题", $this->_userId);
        Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $this->_id, $this->_operator, $title, Application_Model_Tracking::User_Block, "", date("Y-m-d H:i:s"));
        return array("type" => 1, "datetime" => date("Y-m-d H:i:s"));
    }

    public function addAbnormal($cause, $operator) {
        $this->_dateConfrim = date("Y-m-d H:i:s");
        $this->_problemContent .= "<br />悠奇代购(" . date("Y-m-d H:i:s") . ")：" . $cause;
        $this->save();
        Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $this->_id, $operator, "异常处理：" . $cause, Application_Model_Tracking::User_Block, "", date("Y-m-d H:i:s"));
        return array("type" => 1, "problemContent" => $this->_problemContent);
    }

    private $_financial;

    /**
     * 获取手工操作记录
     * @return type
     */
    public function getFinancialCheck() {
        if ($this->_financial == NULL) {
            $this->_financial = Application_Model_FinancialCheckItem::getOnebyObjectTypeObjectId(Application_Model_DomainobjectType::ObjectType_Order, $this->_id);
        }
        return $this->_financial;
    }

    /**
     * 设置手工操作记录
     * @param type $hendworkType
     * @param type $handworkMoney
     * @param type $handworkReason
     */
    public function setHandWork($hendworkType, $handworkMoney, $handworkReason) {
        if ($hendworkType == Application_Model_FinancialCheckItem::Money_Add) {
            if (!$this->AnalysisHandWorkMoney($handworkMoney)) {
                return 2;
            }
        }

        $checkItem = Application_Model_FinancialCheckItem::addCheckItem(Application_Model_DomainobjectType::ObjectType_Order, $this->_id, $handworkMoney, $handworkReason, $this->_operator, $this->_userId, $hendworkType);
        $this->_dateConfrim = date("Y-m-d H:i:s");
        $this->save();
        $title = "为您手工" . $checkItem->getMoneyTypeName() . $handworkMoney . "元(单号:".$this->getOrderNum().")";
        Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $this->_id, $this->_operator, $title, Application_Model_Tracking::User_Block, "", date("Y-m-d H:i:s"));

        $accountObj = Application_Model_UserAccount::load($this->_userId);
        $beforeMoney = $accountObj->money;
        if ($hendworkType == Application_Model_FinancialCheckItem::Money_Add) {
            $accountObj->money = $accountObj->money + $handworkMoney;
            $afterMoney = $beforeMoney + $handworkMoney;
        } else {
            $accountObj->money = $accountObj->money - $handworkMoney;
            $afterMoney = $beforeMoney - $handworkMoney;
        }
        $accountObj->save();

        $userAccountHistory = new Application_Model_UserAccountHistory();
        $userAccountHistory->type = Application_Model_UserAccountHistory::TYPE_MANU;
        $userAccountHistory->beforeMoney = $beforeMoney;
        $userAccountHistory->afterMoney = $afterMoney;
        $userAccountHistory->comment = $title;
        $userAccountHistory->dateCreated = date('Y-m-d H:i:s', time());
        $userAccountHistory->relaseId = $this->_id;
        $userAccountHistory->accountId = $this->_userId;
        $userAccountHistory->State = Application_Model_UserAccountHistory::STATE_MONEY;
        $userAccountHistory->save();
        $messageItem = new Application_Model_Mail();
        $messageItem->title = "尊敬的客户，您好！" . $title;
        $messageItem->userId = $this->_userId;
        $messageItem->type = 2;
        $messageItem->status = Application_Model_Mail::UNREAD;
        $messageItem->message = "尊敬的客户，您好！因您的代购订单(" . $this->getOrderNum() . ")" . $handworkReason . "。" . $title;
        $messageItem->dateCreated = date("Y-m-d H:i:s");
        $messageItem->save();
        Application_Model_Operate::addOperate(0, null, $this->_id, "代购订单设置手工操作：".$title, $this->_userId);
        return 1;
    }

    private function AnalysisHandWorkMoney($handworkMoney) {
        $money = 0;
        foreach ($this->getItems() as $value) {
            if ($value->status == Application_Model_OrderItem::Status_Refund) {
                continue;
            }
            $money = $money + $value->quantity * $value->price;
        }
        if (($money + $this->_shipFee) > $handworkMoney) {
            return true;
        }
        return false;
    }

    /**
     * 活动后代购入库后在给一次成长值，国际运单页面一样
     */
    public function ActivityConsumeExchangeScore() {
        $rechargeItem = Application_Model_RechargeBill::getByUserId($this->_userId, Application_Model_PayBill::PAY_STATUS_SUCCESS, Application_Model_RechargeBill::RechargeActivityStart, Application_Model_RechargeBill::RechargeActivityEnd);
        if (!$rechargeItem) {
            return;
        }
        $sumMoney = 0;
        foreach ($rechargeItem as $rechargeVal) {
            if ($rechargeVal->Money >= 1000) {
                $sumMoney += $rechargeVal->Money;
            }
        }

        $wayMoney = $this->getWayMoney($this->_userId);
        $orderMoney = $this->getOrderMoney($this->_userId);
        if ($sumMoney > ($wayMoney + $orderMoney)) {
            $userItem = Application_Model_UserAccount::addAccount($this->_userId);
            $comment = "代购订单入库，情人节充值活动二次赠送成长值";
            $userItem->MoneyExchangeScore(Application_Model_UserAccount::ExchangeScore_Oreder, $this->_sum, $comment);
        }
    }

    /**
     * 获取活动开始后国际运单消费多少金额
     * @param type $userId 用户Id
     * @return type 运单消费总金额
     */
    private function getWayMoney($userId) {
        $WayBillSearch = new Application_Model_Filter_WayBillSearch();
        $WayBillSearch->userid = $userId;
        $WayBillSearch->status = Application_Model_wayBillItem::STATUS_Complated;
        $WayBillSearch->starttime = Application_Model_RechargeBill::RechargeActivityStart;
        $wayItem = Application_Model_wayBillItem::getDao()->queryAll($WayBillSearch->getSearchFileds());
        $wayMoney = 0;
        foreach ($wayItem as $wayVal) {
            $wayMoney += $wayVal->lastMoney;
        }
        return $wayMoney;
    }

    /**
     * 获取活动开始后代购消费多少金额
     * @param type $userId 用户Id
     * @return type 代购消费总金额
     */
    private function getOrderMoney($userId) {
        $orderSearch = new Application_Model_Filter_OrderSearch();
        $orderSearch->userid = $userId;
        $orderSearch->status = Application_Model_Order::STATUS_INSTORE;
        $orderSearch->starttime = Application_Model_RechargeBill::RechargeActivityStart;
        $orderItem = Application_Model_Order::getDao()->queryAll($orderSearch->getSearchFileds());
        $orderMoney = 0;
        foreach ($orderItem as $orderVal) {
            $orderMoney += $orderVal->Sum;
        }
        return $orderMoney;
    }

    public function getIsTodo() {
        $todoItem = Application_Model_TodoTask::getDao()->queryAll(array("objectType = " => Application_Model_DomainobjectType::ObjectType_Order, " and objectId = " => $this->_id, " and status != " => Application_Model_TodoTask::Object_Complete));
        if (!$todoItem) {
            return false;
        }
        return true;
    }

    public function getBuyidNoname() {
        $arraylist = substr($this->_procureNo, -4);
        switch ($arraylist) {
            case "5899":
                return "uuchcn";
                break;
            case "9936":
                return "悠奇1号";
                break;
            case "6538":
                return "悠奇2号";
                break;
            case "3662":
                return "悠奇3号";
                break;
            case "3852":
                return "悠奇4号";
                break;
            case "5382":
                return "悠奇6号";
                break;
            default :
                return "不是淘宝";
                break;
        }
    }

    /**
     *  获取代购退款金额
     */
    public function getMoneyGroup() {
        $object = $this->getshipdetail();
        $money = 0;
        foreach ($object as $objectVal) {
            if ($objectVal->status != 1) {
                continue;
            }
            $money += $objectVal->price * $objectVal->quantity;
        }
        return $money;
    }

    public function getTrackInfo($operateType) {
        return Application_Model_Tracking::getOneByObjectTypeIdOperateType(Application_Model_DomainobjectType::ObjectType_Order, $this->_id, $operateType);
    }

}

class Application_Model_OrderParent extends Application_Model_Order implements Application_Model_PayInterface {

    protected $_ids;
    protected $_orders;

    /**
     * 根据几个ID，创建一个空订单，供支付使用
     */
    public static function createByOrderIds($ids) {
        $splitIds = split(',', $ids);
        $order = new Application_Model_OrderParent();
        $order->Ids = $splitIds;
        $orders = array();
        foreach ($splitIds as $id) {
            $item = Application_Model_Order::load($id);
            $orders[] = $item;
        }
        $order->_orders = $orders;
        return $order;
    }

    public function getBillNo() {
        return $this->_orders[0]->OrderNum;
    }

    public function setPaid() {
        foreach ($this->_orders as $order) {
            $order->setPaid();
        }
    }

    public function getMoney() {
        $sum = 0;
        foreach ($this->_orders as $order) {
            $sum += ($order->Sum - $order->Discount);
        }
        return $sum;
    }

    public function getPayName() {
        return '代购订单';
    }

    public function getPayDescription() {
        return $this->getPayName();
    }

    public function canPay($userId) {
        foreach ($this->_orders as $order) {
            if (!$order->canPay($userId)) {
                return FALSE;
            }
        }
        return TRUE;
    }

    public function isRepeatPay() {
        foreach ($this->_orders as $order) {
            if ($order->_status == Application_Model_Order::STATUS_PAYING) {
                return true;
            }
            return false;
        }
    }

    public function getPayCommen() {
        $orderNo = "";
        foreach ($this->_orders as $order) {
            $orderNo .= "代购流水号：U" . substr($order->DateCreated, 0, 4) . $order->Id . substr($order->DateCreated, 17, 1) . ",";
        }
        return $orderNo;
    }

    public function save() {
        foreach ($this->_orders as $order) {
            $order->save();
        }
    }

    /**
     * 获取商品信息
     * @return type
     */
    public function getshipdetail() {
        return Application_Model_OrderItem::getByOrderId($this->_id);
    }

    public static function sumOrderMoney($userId) {
        $where['userId = '] = $userId;
        $where[' and status > '] = 0;
        return self::getDao()->sum($where);
    }

    public function returnMoney($reChangeMoney) {
        try {
            $db = Application_Model_OrderItem::getDao();
            $db->beginTran();
            $comment = "代购订单:" . $this->getOrderNum() . '退货成功，退款';
            $accountObj = Application_Model_UserAccount::load($this->_userId);
            $beforeMoney = $accountObj->money;
            $accountObj->money = $accountObj->money + $reChangeMoney;
            $accountObj->save();

            $afterMoney = $beforeMoney + $reChangeMoney;
            $userAccountHistory = new Application_Model_UserAccountHistory();
            $userAccountHistory->type = Application_Model_UserAccountHistory::TYPE_RETURNMONEY;
            $userAccountHistory->beforeMoney = $beforeMoney;
            $userAccountHistory->afterMoney = $afterMoney;
            $userAccountHistory->comment = $comment;
            $userAccountHistory->dateCreated = date('Y-m-d H:i:s', time());
            $userAccountHistory->relaseId = $this->_id;
            $userAccountHistory->accountId = $this->_userId;
            $userAccountHistory->State = Application_Model_UserAccountHistory::STATE_MONEY;
            $userAccountHistory->save();
            $db->commit();
            return 1;
        } catch (Exception $exc) {
            $db->rollBack();
            return 0;
        }
    }


}
